package com.fenghongzhang.day008;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class FentTextView extends View {

    private static final String TAG = "FentTextView";
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private String text;
    private float dimension;
    //动态创建
    public FentTextView(Context context) {
        super(context);
    }

    //用到xml布局中
    public FentTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FentTextView);
        text = typedArray.getString(R.styleable.FentTextView_text);
        dimension = typedArray.getDimension(R.styleable.FentTextView_size, 100);
    }

    //测量
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);



        /**
         * 0000 0011
         * 0000 0101
         * 十进制 0
         * 二进制 0000  0000
         *
         * 1
         * 0000 0001
         *
         * 2
         * 0000 0010
         *
         * 2 << 1 = ?
         * 0000 0100
         *
         * 4 >> 1
         * 2 4 8 16 32 64
         *
         * 00000 0000 000000 00000 000000
         *
         *
         */

        int width = getMyViewSize(300, widthMeasureSpec);
        int height = getMyViewSize(300, heightMeasureSpec);

        setMeasuredDimension(width,height);

    }


    //控制子view如何拜访.
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

    }

    private int getMyViewSize(int defaultSize, int measureSpec) {
        int result = defaultSize;
        //解封模式和尺寸值
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        switch (specMode) {
            case MeasureSpec.AT_MOST:
                //指定一个值
                result = defaultSize;
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setTextSize(dimension);
        canvas.drawText(text,100,100,paint);

    }
}
